package com.bf.electroplating.service.impl;

import com.bf.electroplating.pojo.entity.*;
import com.bf.electroplating.pojo.vo.rain.*;
import com.bf.electroplating.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前端雨水管网图环保管理驾驶舱数据服务实现类
 */
@Slf4j
@Service
public class FrontRainServiceImpl implements IFrontRainService {

    @Autowired
    private ComCompanyService comCompanyService;

    @Autowired
    private ComWorkshopService comWorkshopService;

    @Autowired
    private ComProductionService comProductionService;

    @Autowired
    private ComEnvironmentallyFacilityService comEnvironmentallyFacilityService;

    @Override
    public ParkOverviewDataVO getParkOverviewData() {
        ParkOverviewDataVO data = new ParkOverviewDataVO();
        
        // 园区基本信息
        ParkInfoVO parkInfo = new ParkInfoVO();
        parkInfo.setParkName("武义电镀产业园");
        parkInfo.setLocation("浙江省武义县泉溪镇泉湖工业功能区");
        parkInfo.setPurpose("整合提升电镀产业");
        parkInfo.setPlannedArea("39.06公顷");
        parkInfo.setOperationalStatus("15家企业正式投产，整合了18家分散企业");
        
        // 统计数据 - 从数据库获取
        Map<String, Object> statistics = new HashMap<>();
        long enterpriseCount = comCompanyService.count();
        long workshopCount = comWorkshopService.count();
        long productionLineCount = comProductionService.count();
        
        statistics.put("enterpriseCount", (int) enterpriseCount);
        statistics.put("workshopCount", (int) workshopCount);
        statistics.put("productionLineCount", (int) productionLineCount);
        
        // 行业分类统计
        Map<String, Object> industryStats = new HashMap<>();
        industryStats.put("electroplating", (int) (enterpriseCount * 0.9)); // 假设90%是电镀企业
        industryStats.put("wastewater", (int) (enterpriseCount * 0.1)); // 假设10%是污水处理企业
        
        data.setParkInfo(parkInfo);
        data.setStatistics(statistics);
        data.setIndustryStats(industryStats);
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public RainAlarmHandlingDataVO getAlarmHandlingData() {
        RainAlarmHandlingDataVO data = new RainAlarmHandlingDataVO();
        
        // 预警统计 - 模拟数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalAlarms", 700 + new Random().nextInt(100));
        statistics.put("handledAlarms", 100 + new Random().nextInt(50));
        statistics.put("unhandledAlarms", 600 + new Random().nextInt(100));
        data.setStatistics(statistics);
        
        // 预警详细列表
        List<RainAlarmVO> alarmList = new ArrayList<>();
        String[] alarmTypes = {"PH值异常", "流量异常", "电导率异常", "温度异常"};
        String[] deviceNames = {"监测设备A", "监测设备B", "监测设备C", "监测设备D"};
        String[] statuses = {"已处置", "未处置"};
        String[] colors = {"green", "red"};
        
        for (int i = 0; i < 3; i++) {
            RainAlarmVO alarm = new RainAlarmVO();
            alarm.setAlarmType(alarmTypes[new Random().nextInt(alarmTypes.length)]);
            alarm.setDeviceName(deviceNames[new Random().nextInt(deviceNames.length)]);
            alarm.setAlarmValue(1 + new Random().nextInt(5));
            alarm.setAlarmThreshold(2 + new Random().nextInt(3));
            alarm.setHandlingStatus(statuses[new Random().nextInt(statuses.length)]);
            alarm.setStatusColor(colors[new Random().nextInt(colors.length)]);
            alarmList.add(alarm);
        }
        
        data.setAlarmList(alarmList);
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public DeviceStatisticsDataVO getDeviceStatistics() {
        DeviceStatisticsDataVO data = new DeviceStatisticsDataVO();
        
        // 从环境设施表获取设备数量
        long totalDevices = comEnvironmentallyFacilityService.count();
        long onlineDevices = (long) (totalDevices * 0.98); // 假设98%在线
        long offlineDevices = totalDevices - onlineDevices;
        
        data.setTotalDevices((int) totalDevices);
        data.setOnlineDevices((int) onlineDevices);
        data.setOfflineDevices((int) offlineDevices);
        
        // 计算在线率
        double onlineRate = totalDevices > 0 ? (double) onlineDevices / totalDevices * 100 : 0;
        data.setOnlineRate(Math.round(onlineRate * 100.0) / 100.0);
        
        // 设备状态分布
        Map<String, Object> deviceStatus = new HashMap<>();
        deviceStatus.put("online", onlineDevices);
        deviceStatus.put("offline", offlineDevices);
        deviceStatus.put("maintenance", 0);
        data.setDeviceStatus(deviceStatus);
        
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public RiverOutletsDataVO getRiverOutletsData(int outletId) {
        RiverOutletsDataVO data = new RiverOutletsDataVO();
        
        // 排口基本信息
        OutletInfoVO outletInfo = new OutletInfoVO();
        outletInfo.setOutletId(outletId);
        outletInfo.setOutletName("排口" + outletId);
        outletInfo.setLocation("园区" + outletId + "号排口");
        
        // 闸阀状态
        ValveStatusVO valveStatus = new ValveStatusVO();
        valveStatus.setStatus("开");
        valveStatus.setStatusColor("green");
        valveStatus.setType("手自一体闸阀");
        
        data.setOutletInfo(outletInfo);
        data.setValveStatus(valveStatus);
        
        // 12个月的趋势数据
        List<String> months = Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", 
                                          "7月", "8月", "9月", "10月", "11月", "12月");
        
        // PH值和电导率数据（根据排口不同，数据略有差异）
        List<Integer> phValues = new ArrayList<>();
        List<Integer> conductivityValues = new ArrayList<>();
        
        for (int i = 0; i < 12; i++) {
            phValues.add(40 + outletId * 2 + new Random().nextInt(20));
            conductivityValues.add(30 + outletId + new Random().nextInt(20));
        }
        
        data.setMonths(months);
        data.setPhValues(phValues);
        data.setConductivityValues(conductivityValues);
        data.setUnit("%");
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public EmergencyPoolDataVO getEmergencyPoolData(String poolType) {
        EmergencyPoolDataVO data = new EmergencyPoolDataVO();
        
        if ("emergency".equals(poolType)) {
            // 应急池数据
            RainPoolDataVO emergencyPool = new RainPoolDataVO();
            emergencyPool.setPoolName("应急池");
            emergencyPool.setCapacity("131立方");
            emergencyPool.setAvailableCapacity("31立方");
            emergencyPool.setCurrentLevelRatio(60 + new Random().nextInt(10));
            emergencyPool.setLiquidLevel(60 + new Random().nextInt(10));
            emergencyPool.setStatus("正常");
            emergencyPool.setStatusColor("green");
            data.setPoolData(emergencyPool);
        } else if ("initialRain".equals(poolType)) {
            // 初雨池数据
            RainPoolDataVO initialRainPool = new RainPoolDataVO();
            initialRainPool.setPoolName("初雨池");
            initialRainPool.setCapacity("200立方");
            initialRainPool.setAvailableCapacity("80立方");
            initialRainPool.setCurrentLevelRatio(35 + new Random().nextInt(15));
            initialRainPool.setLiquidLevel(35 + new Random().nextInt(15));
            initialRainPool.setStatus("正常");
            initialRainPool.setStatusColor("green");
            data.setPoolData(initialRainPool);
        }
        
        data.setPoolType(poolType);
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public MapNavigationDataVO getMapNavigationData(String viewType) {
        MapNavigationDataVO data = new MapNavigationDataVO();
        
        // 导航选项
        List<NavigationOptionVO> navigationOptions = new ArrayList<>();
        
        NavigationOptionVO option1 = new NavigationOptionVO();
        option1.setKey("enterprises");
        option1.setName("园区企业");
        option1.setActive("enterprises".equals(viewType));
        option1.setColor("enterprises".equals(viewType) ? "blue" : "gray");
        navigationOptions.add(option1);
        
        NavigationOptionVO option2 = new NavigationOptionVO();
        option2.setKey("rainwaterNetwork");
        option2.setName("雨水管网图");
        option2.setActive("rainwaterNetwork".equals(viewType));
        option2.setColor("rainwaterNetwork".equals(viewType) ? "orange" : "gray");
        navigationOptions.add(option2);
        
        NavigationOptionVO option3 = new NavigationOptionVO();
        option3.setKey("onlineMonitoring");
        option3.setName("在线监控");
        option3.setActive("onlineMonitoring".equals(viewType));
        option3.setColor("onlineMonitoring".equals(viewType) ? "blue" : "gray");
        navigationOptions.add(option3);
        
        // 地图数据
        Map<String, Object> mapData = new HashMap<>();
        mapData.put("centerLongitude", 119.8);
        mapData.put("centerLatitude", 28.9);
        mapData.put("zoomLevel", 15);
        mapData.put("viewType", viewType);
        
        // 根据视图类型返回不同的数据
        if ("enterprises".equals(viewType)) {
            // 园区企业数据 - 从数据库获取
            List<ComCompany> companies = comCompanyService.list();
            List<Map<String, Object>> enterprises = companies.stream()
                    .limit(17)
                    .map(company -> {
                        Map<String, Object> enterprise = new HashMap<>();
                        enterprise.put("id", company.getId());
                        enterprise.put("name", company.getCompanyName());
                        enterprise.put("longitude", 119.8 + (Math.random() - 0.5) * 0.01);
                        enterprise.put("latitude", 28.9 + (Math.random() - 0.5) * 0.01);
                        enterprise.put("type", "电镀");
                        return enterprise;
                    })
                    .collect(Collectors.toList());
            mapData.put("enterprises", enterprises);
        } else if ("rainwaterNetwork".equals(viewType)) {
            // 雨水管网数据 - 模拟数据
            List<Map<String, Object>> networkNodes = new ArrayList<>();
            for (int i = 1; i <= 20; i++) {
                Map<String, Object> node = new HashMap<>();
                node.put("id", i);
                node.put("name", "管网节点" + i);
                node.put("longitude", 119.8 + (Math.random() - 0.5) * 0.01);
                node.put("latitude", 28.9 + (Math.random() - 0.5) * 0.01);
                node.put("status", Math.random() > 0.1 ? "正常" : "异常");
                networkNodes.add(node);
            }
            mapData.put("networkNodes", networkNodes);
        } else if ("onlineMonitoring".equals(viewType)) {
            // 在线监控数据 - 从环境设施表获取
            List<ComEnvironmentallyFacility> facilities = comEnvironmentallyFacilityService.list();
            List<Map<String, Object>> monitoringPoints = facilities.stream()
                    .limit(25)
                    .map(facility -> {
                        Map<String, Object> point = new HashMap<>();
                        point.put("id", facility.getId());
                        point.put("name", facility.getEnvironmentalFacilityName());
                        point.put("longitude", 119.8 + (Math.random() - 0.5) * 0.01);
                        point.put("latitude", 28.9 + (Math.random() - 0.5) * 0.01);
                        point.put("status", Math.random() > 0.05 ? "在线" : "离线");
                        point.put("phValue", 6.5 + Math.random() * 2);
                        point.put("conductivity", 100 + Math.random() * 500);
                        return point;
                    })
                    .collect(Collectors.toList());
            mapData.put("monitoringPoints", monitoringPoints);
        }
        
        data.setNavigationOptions(navigationOptions);
        data.setMapData(mapData);
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public RealtimeMonitoringDataVO getRealtimeMonitoringData() {
        RealtimeMonitoringDataVO data = new RealtimeMonitoringDataVO();
        
        // 实时时间
        data.setCurrentTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        data.setCurrentDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
        
        // 天气信息
        WeatherVO weather = new WeatherVO();
        weather.setCondition("晴转多云");
        weather.setTemperature("18-26°C");
        weather.setIcon("sun-cloud");
        data.setWeather(weather);
        
        // 实时监测数据
        List<RealtimeDataVO> realtimeData = new ArrayList<>();
        
        for (int i = 1; i <= 3; i++) {
            RealtimeDataVO realtimeDataItem = new RealtimeDataVO();
            realtimeDataItem.setLocation("排口" + i);
            realtimeDataItem.setPhValue(6.5 + Math.random() * 0.8);
            realtimeDataItem.setConductivity(150 + Math.random() * 150);
            realtimeDataItem.setFlowRate(40 + Math.random() * 30);
            realtimeDataItem.setStatus("正常");
            realtimeDataItem.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
            realtimeData.add(realtimeDataItem);
        }
        
        data.setRealtimeData(realtimeData);
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }

    @Override
    public ComprehensiveSituationDataVO getComprehensiveSituationData() {
        ComprehensiveSituationDataVO data = new ComprehensiveSituationDataVO();
        
        // 综合统计 - 从数据库获取
        long totalEnterprises = comCompanyService.count();
        long totalDevices = comEnvironmentallyFacilityService.count();
        long onlineDevices = (long) (totalDevices * 0.98);
        
        Map<String, Object> comprehensiveStats = new HashMap<>();
        comprehensiveStats.put("totalEnterprises", (int) totalEnterprises);
        comprehensiveStats.put("totalDevices", (int) totalDevices);
        comprehensiveStats.put("onlineDevices", (int) onlineDevices);
        comprehensiveStats.put("totalAlarms", 700 + new Random().nextInt(100));
        comprehensiveStats.put("handledAlarms", 100 + new Random().nextInt(50));
        comprehensiveStats.put("emergencyPoolLevel", 60 + new Random().nextInt(10));
        comprehensiveStats.put("initialRainPoolLevel", 35 + new Random().nextInt(15));
        
        // 环境质量指标
        Map<String, Object> environmentalQuality = new HashMap<>();
        environmentalQuality.put("airQuality", "良好");
        environmentalQuality.put("waterQuality", "达标");
        environmentalQuality.put("noiseLevel", "正常");
        environmentalQuality.put("overallRating", "优秀");
        
        // 安全状态
        Map<String, Object> safetyStatus = new HashMap<>();
        safetyStatus.put("fireSafety", "正常");
        safetyStatus.put("emergencyResponse", "就绪");
        safetyStatus.put("equipmentSafety", "正常");
        safetyStatus.put("environmentalSafety", "正常");
        
        data.setComprehensiveStats(comprehensiveStats);
        data.setEnvironmentalQuality(environmentalQuality);
        data.setSafetyStatus(safetyStatus);
        data.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return data;
    }
}
